﻿<template>
    <div class="esProductChannelPlanToday-container">
        <el-dialog v-model="state.isShowDialog" draggable width="769px">
            <template #header>
                <div style="color: #fff">
                    <el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
                        <ele-Edit/>
                    </el-icon>
                    <span> {{ props.title }} </span>
                </div>
            </template>
            <el-form :model="state.ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="产品渠道" prop="productChannelId">
                            <el-select v-model="state.selectProductChannel" filterable placeholder="请选择" class="w100"
                                       :disabled='props.title=="编辑"'>
                                <el-option v-for='item in state.productChannelDict' :key='item.value'
                                           :label='item.label'
                                           :value='item'/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="互斥周期" prop="phoneUniqueMonthly">
                            <el-input-number v-model="state.ruleForm.phoneUniqueMonthly" :min="0" :max="9999"
                                             controls-position="right" placeholder="请输入手机号业务互斥周期：月单位"
                                             class="w100"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="管控级别" prop="controlLevel">
                            <el-input-number v-model="state.ruleForm.controlLevel" :min="0" :max="9999"
                                             controls-position="right" placeholder="请输入管控级别" class="w100"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="状态" >
                            <el-select v-model="state.ruleForm.status" placeholder="请输入状态" class="w100">
                                <el-option label="启用" :value="1" ></el-option>
                                <el-option label="停用" :value="2" :disabled="true"></el-option>
                                <el-option label="到量" :value="3" ></el-option>
                                <el-option label="短期关停" :value="4" ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label='日期'>
                            <el-date-picker
                                class='w100'
                                v-model='state.DateRange'
                                type='datetimerange'
                                range-separator='至'
                                start-placeholder='开始日期'
                                end-placeholder='结束日期'
                                :format="valueAndDateFormat"
                                :value-format="valueAndDateFormat"
                                :default-time="defaultTime"
                                :disabled-date="disabledDate"
                                :disabled-hours="disabledHours"
                                :disabled-minutes="disabledMinutes"
                                :disabled-seconds="disabledSeconds"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="到量控制" prop="arrivalType">
                            <el-radio-group v-model="state.ruleForm.arrivalType">
                                <el-radio :label="1">请求</el-radio>
                                <el-radio :label="2">用户</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="7" :md="7" :lg="7" :xl="7" class="mb20">
                        <el-form-item label="请求限制" prop="requestLimit">
                            <el-input-number v-model="state.ruleForm.requestLimit" placeholder="请输入请求限制" :min="0"
                                             controls-position="right" class="w100"
                                             :disabled="state.ruleForm.arrivalType !== 1"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="7" :md="7" :lg="7" :xl="7" class="mb20">
                        <el-form-item label="用户限制" prop="userLimit">
                            <el-input-number v-model="state.ruleForm.userLimit" placeholder="请输入用户限制" :min="0"
                                             controls-position="right" class="w100"
                                             :disabled="state.ruleForm.arrivalType !== 2"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="备注">
                            <el-input v-model="state.ruleForm.remark" placeholder="请输入备注内容" clearable
                                      type="textarea"
                                      maxlength="255" :autosize="{ minRows: 2 }"/>
                        </el-form-item>
                    </el-col>
                    <el-divider border-style="dashed"/>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-button icon="ele-Plus" type="primary" plain @click="addExtOrgRow"> 增加省份与屏蔽城市
                        </el-button>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <template
                            v-if="state.ruleForm.provinceList != undefined && state.ruleForm.provinceList.length > 0">
                            <el-row :gutter="35" v-for="(v, k) in state.ruleForm.provinceList" :key="k">
                                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                    <el-form-item label="省份" :prop="`province`">
                                        <template #label>
                                            <el-button icon="ele-Delete" type="danger" circle plain size="small"
                                                       @click="deleteExtOrgRow(k)"/>
                                            <span class="ml5">省份</span>
                                        </template>
                                        <el-select v-model="state.ruleForm.provinceList[k].province" filterable
                                                   placeholder="省份"
                                                   class="w100">
                                            <el-option v-for='item in optionDict.provinceDict' :key='item.value'
                                                       :label='item.label' :value='item.value'/>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                    <el-form-item label="屏蔽城市" prop="screenCity">
                                        <el-input v-model="state.ruleForm.provinceList[k].screenCity"
                                                  placeholder="请输入屏蔽城市"
                                                  clearable></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </template>
                        <el-empty :image-size="80" description="空数据" v-else></el-empty>
                    </el-col>
                    <!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="备注">
                            <el-input v-model="state.ruleForm.remark" placeholder="请输入备注内容" clearable type="textarea"
                                maxlength="255" :autosize="{ minRows: 2 }" />
                        </el-form-item>
                    </el-col> -->

                </el-row>
            </el-form>
            <template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel" size="default">取 消</el-button>
					<el-button type="primary" @click="submit" size="default">确 定</el-button>
				</span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="editEsProductChannelPlanToday">

import {computed, reactive, ref} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import type {FormRules} from "element-plus";
import mittBus from '/@/utils/mitt';
import {optionDict} from '/@/const/dict';
import {EsProductChannelPlanToday, sysBaseDict} from '/@/api/models';
import SysEsProductChannelPlanTodayApi from '/@/api/exocytosis/productChannelPlanToday';
import commonFunction from '/@/utils/commonFunction';
import SysEsProductChannelApi from '/@/api/exocytosis/productChannel';
import dayjs from "dayjs";

// 定义变量内容
const {generateRandomLowercaseString} = commonFunction();
const props = defineProps({
    title: String,
});

// 获取当前时间
const now = dayjs();

// 设置默认时间（优化版）
const defaultTime = computed(() => {
    // 当日开始时间设置为当前时间
    const startTime = new Date(now.valueOf());

    // 当日结束时间设置为23:59:59
    const endTime = new Date();
    endTime.setHours(23, 59, 59, 0);

    return [startTime, endTime];
});

// 日期格式设置
const valueAndDateFormat = 'YYYY-MM-DD HH:mm:ss';

const ruleFormRef = ref();
const state = reactive({
    DateRange: [],
    isShowDialog: false,
    ruleForm: {} as EsProductChannelPlanToday,
    selectProductChannel: null,
    productChannelDict: [] as sysBaseDict[],
});

// 删除非必填规则
const rules = ref<FormRules>({
    merchantId: [{required: true, message: '请输入商户ID！', trigger: 'blur',},],
    productId: [{required: true, message: '请输入产品Id！', trigger: 'blur',},],
    channelId: [{required: true, message: '请输入渠道Id！', trigger: 'blur',},],
    productChannelId: [{required: true, message: '请输入产品渠道ID！', trigger: 'blur',},],
    productChannelCode: [{required: true, message: '请输入分配的产品渠道Key！', trigger: 'blur',},],
    status: [{required: true, message: '请选择状态 0:未知 1:启用 2:停用 3:到量 4:短期关停！', trigger: 'change',},],
});

// 打开弹窗
const openDialog = async (row: EsProductChannelPlanToday, conDition: string) => {
    await productChannelQuery();
    state.selectProductChannel = state.productChannelDict.find((item) => {
        return item.value === row.productChannelId;
    }) ?? null;
    if (conDition == 'add') {
        state.ruleForm = row;
        state.isShowDialog = true;
        state.ruleForm.productChannelCode = generateRandomLowercaseString(6);
        state.ruleForm.provinceList = [{}];
        // 使用 .value 获取计算属性的实际值
        state.DateRange = defaultTime.value.map(date =>
            dayjs(date).format('YYYY-MM-DD HH:mm:ss')
        );
    } else {
        state.ruleForm = row;
        state.isShowDialog = true;
        state.DateRange = [row.startTime, row.endTime];
        state.ruleForm.provinceList = [{province: state.ruleForm.province, screenCity: state.ruleForm.screenCity}];
    }
};

// 关闭弹窗
const closeDialog = () => {
    state.DateRange = [];
    mittBus.emit('submitRefresh');
    state.isShowDialog = false;
};

// 取消
const cancel = () => {
    state.isShowDialog = false;
};

// 提交
const submit = () => {
    if (state.ruleForm.arrivalType === 1)
        state.ruleForm.userLimit = 0;
    else
        state.ruleForm.requestLimit = 0;

    state.ruleForm.startTime = state.DateRange[0];
    state.ruleForm.endTime = state.DateRange[1];
    state.ruleForm.productChannelId = state.selectProductChannel?.value;
    state.ruleForm.productChannelCode = state.selectProductChannel?.exValue;
    ruleFormRef.value.validate(async (valid: boolean, fields?: any) => {
        if (valid) {
            let res;
            if (state.ruleForm.id != undefined && state.ruleForm.id > 0) {
                res = await SysEsProductChannelPlanTodayApi().editPost(state.ruleForm);
            } else {
                res = await SysEsProductChannelPlanTodayApi().addPost(state.ruleForm);
            }
            if (res.data.resCode != '0000')
                ElMessage.error(res.data.resMessage);
            else {
                ElMessage.success("操作成功");
                closeDialog();
            }
        } else {
            ElMessage({
                message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
                type: "error",
            });
        }
    });
};

// 增加附属机构行
const addExtOrgRow = () => {
    if (state.ruleForm.provinceList == undefined) state.ruleForm.provinceList = [];
    state.ruleForm.provinceList?.push({});
};

// 删除附属机构行
const deleteExtOrgRow = (k: number) => {
    if (state.ruleForm.provinceList.length == 1) {
        ElMessage({
            message: `最少选中一个省份`,
            type: "error",
        });
        return;
    }
    state.ruleForm.provinceList?.splice(k, 1);
};

// 产品渠道字典
const productChannelQuery = async () => {
    await SysEsProductChannelApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.productChannelDict = res.data.result ?? [];
    });
};

// 禁用日期选择（不允许修改年月日）
const disabledDate = (date) => {
    return true; // 禁用所有日期选择
};

// 获取当前时间
const isToday = computed(() => {
    return dayjs(state.DateRange[0]).isSame(now, 'day');
});

// 禁用小时
const disabledHours = (which) => {
    if (!isToday.value) return []; // 非当日不禁用任何小时

    const currentHour = now.hour();
    const disabledHours = [];

    // 如果是开始时间选择器
    if (which === 'start') {
        for (let i = 0; i < currentHour; i++) {
            disabledHours.push(i); // 禁用当前时间之前的小时
        }
    }

    return disabledHours;
};

// 禁用分钟
const disabledMinutes = (selectedHour, which) => {
    if (!isToday.value) return []; // 非当日不禁用任何分钟

    const currentMinute = now.minute();
    const disabledMinutes = [];

    // 如果是开始时间选择器且选中的是当前小时
    if (which === 'start' && selectedHour === now.hour()) {
        for (let i = 0; i < currentMinute; i++) {
            disabledMinutes.push(i); // 禁用当前时间之前的分钟
        }
    }

    return disabledMinutes;
};

// 禁用秒钟
const disabledSeconds = (selectedHour, selectedMinute, which) => {
    if (!isToday.value) return []; // 非当日不禁用任何秒钟

    const currentSecond = now.second();
    const disabledSeconds = [];

    // 如果是开始时间选择器且选中的是当前小时和分钟
    if (which === 'start' && selectedHour === now.hour() && selectedMinute === now.minute()) {
        for (let i = 0; i < currentSecond; i++) {
            disabledSeconds.push(i); // 禁用当前时间之前的秒钟
        }
    }

    return disabledSeconds;
};

// 导出对象 将属性或者函数暴露给父组件
defineExpose({openDialog});
</script>

<style lang="scss" scoped>
.higlabel {
    :deep(label) {
        display: flex;
        align-items: center;
    }
}
</style>
